import openpyxl
from openpyxl import Workbook
from settings import OUTPUT_DATA_PATH, ORIGIN_DATA_PATH
from settings import OUTPUT_UP_HOMEPAGE_DETAIL
from item.up_info import UPInfo
from item.video_info import VideoInfo
import re

def save_links(name, links):
    wb = Workbook()
    ws = wb.active
    print("-------saving data-------")
    l = len(links)
    for index in range(l):
        line = [links[index]]
        try:
            ws.append(line)
        except Exception as e:
            print(e)
    print("will begin write")
    try:
        wb.save(ORIGIN_DATA_PATH + name)
    except Exception as e:
        print(e)
        wb.close()
    else:
        print(name + ' save √! items = ', len(links))
        wb.close()

def add_links(name, items):
    try:
        wb = openpyxl.load_workbook(ORIGIN_DATA_PATH + name)
    except Exception as e:
        wb = openpyxl.Workbook()
    ws = wb.active
    print("-------saving data-------")
    l = len(items)
    for index in range(l):
        line = [items[index]['link'], items[index]['uid'], items[index]['video_time'], items[index]['target_video_num']]
        try:
            ws.append(line)
        except Exception as e:
            print(e)
    print("will begin write")
    try:
        wb.save(ORIGIN_DATA_PATH + name)
    except Exception as e:
        print(e)
        wb.close()
    else:
        print(name + ' save √! items = ', len(items))
        wb.close()

def add_up_item(name, item:UPInfo):
    wb = openpyxl.load_workbook(OUTPUT_DATA_PATH + name)
    ws = wb.active
    print("-------saving data-------")
    line = [item.uid, item.follow, item.fans, item.liked, item.played, item.charge_num, item.create_video_num]
    try:
        ws.append(line)
    except Exception as e:
        print(e)
    print("will begin write")
    try:
        wb.save(OUTPUT_DATA_PATH + name)
    except Exception as e:
        print(e)
        wb.close()
    else:
        wb.close()

def add_video_detail_item(name, item:VideoInfo):
    wb = openpyxl.load_workbook(OUTPUT_DATA_PATH + name)
    ws = wb.active
    print("-------saving data-------")
    line = [item.uid, item.vid, item.title, item.played, item.liked, item.coin, item.share, item.video_time, ';'.join(item.tag), item.publish_time, item.scrape_time]
    try:
        ws.append(line)
    except Exception as e:
        print(e)
    print("will begin write")
    try:
        wb.save(OUTPUT_DATA_PATH + name)
    except Exception as e:
        print(e)
        wb.close()
    else:
        wb.close()